<template>
  <div class="me-box">
    <el-row>
      <el-col :span="8">
        <el-card class="box-card">
          <div class="form-style">
            <el-button
            type="primary"
            @click="showDialog('添加')"
            >添加新数据</el-button>

            <batchAddBtn :Year="YearTitle" @importData="importData"></batchAddBtn>

            <el-button
            type="info"
            @click="$exportExcel(tableData, YearTitle)"
            >{{ `导出${YearTitle}年数据` }}</el-button>
          </div>
        </el-card>
      </el-col>

      <MiddleAssembly @getTitle="getTitleFn"></MiddleAssembly>
      <RightAssembly
        :target="target[YearTitle]">
      </RightAssembly>
    </el-row>
    <!-- 卡片 -->

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      :summary-method="getSummaries"
      show-summary
      class="el-table-box"
      max-height="500"
      border
      >
      <el-table-column
        type="index"
        label="序号"
        width="80"
        >
      </el-table-column>

      <el-table-column
        prop="gzyf"
        label="工作月份"
        >
      </el-table-column>

      <el-table-column
        prop="dsgz"
        label="到手工资">
      </el-table-column>

      <el-table-column
        prop="shfy"
        label="生活费用">
      </el-table-column>

      <el-table-column
        prop="fxhkyf"
        label="发薪(还款)月份">
      </el-table-column>

      <el-table-column
        prop="xfmx"
        label="消费明细"
        width="214"
        >
        <template slot-scope="scope">
          <p v-for="item in scope.row.xfmx.split(',')" :key="item">{{ item }}</p>
        </template>
      </el-table-column>

      <el-table-column
        prop="yjhk"
        label="预计还款">
      </el-table-column>

      <el-table-column
        prop="tag"
        label="状态"
        filter-placement="bottom-end"
        width="100">
        <template slot-scope="scope">
          <el-tag
          :type="scope.row.tag === '完成' ? 'success' : 'danger'"
          effect="dark"
          disable-transitions>{{scope.row.tag}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
      fixed="right"
      label="操作"
      width="111">
      <template slot-scope="scope">
        <el-button
        @click="showDialog('编辑',scope)"
        type="primary"
        icon="el-icon-edit"
        circle
        >
        </el-button>

        <el-button
        @click="delRow(scope)"
        type="danger"
        icon="el-icon-delete"
        circle
        >
        </el-button>

      </template>
    </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="50%"
    @close="closeDialog"
    :close-on-click-modal=false
    >
      <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工作月份" prop="gzyf">
            <el-input v-model="ruleForm.gzyf"
            @keydown.enter.native="submitForm"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到手工资" prop="dsgz">
            <el-input v-model="ruleForm.dsgz"
            @keydown.enter.native="submitForm"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计还款" prop="yjhk">
            <el-input v-model="ruleForm.yjhk"
            @keydown.enter.native="submitForm"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生活费用" prop="shfy">
            <el-input v-model="ruleForm.shfy"
            @keydown.enter.native="submitForm"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发薪月份" prop="fxhkyf">
            <el-input v-model="ruleForm.fxhkyf"
            @keydown.enter.native="submitForm"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消费明细" prop="xfmx">
            <el-input placeholder="以英文 , 分割消费项目" v-model="ruleForm.xfmx"
            @keydown.enter.native="submitForm"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
        <el-form-item label="状态" prop="tag" v-if="dialogTitle==='编辑'">
          <el-radio-group v-model="ruleForm.tag">
            <el-radio label="完成"></el-radio>
            <el-radio label="未完成"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
        type="primary"
        @click="submitForm"
        >
        确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import batchAddBtn from '@/views/plan/batchAddBtn.vue'
export default {
  name: 'CG',
  components: {
    batchAddBtn
  },
  data () {
    return {
      // 目标
      target: {
        2023: '目标：二零二三年还债1万元',
        2024: '目标：还清所有债务',
        2025: '目标：攒钱买车',
        2026: '目标：攒彩礼钱'
      },
      // 选择的年
      YearTitle: '',
      dialogTitle: '',
      dialogVisible: false,
      currentRow: '',
      // 输入信息
      ruleForm: {
        gzyf: '',
        dsgz: '',
        yjhk: '',
        shfy: '',
        fxhkyf: '',
        xfmx: '',
        tag: '未完成'
      },
      // 输入的信息规则
      rules: {
        gzyf: [{ required: true, message: '请输入工作月份', trigger: 'blur' }],
        dsgz: [{ required: true, message: '请输入到手工资', trigger: 'blur' }],
        yjhk: [{ required: true, message: '请输入预计还款', trigger: 'blur' }],
        shfy: [{ required: true, message: '请输入生活费用', trigger: 'blur' }],
        fxhkyf: [{ required: true, message: '请输入发薪(还款)月份', trigger: 'blur' }],
        xfmx: [{ required: true, message: '请输入消费明细', trigger: 'blur' }]
      },
      // 表格数据
      tableData: []
    }
  },
  mounted () {
    this.updatedItem()
  },
  watch: {
    YearTitle (newValue) {
      this.tableData = []
      this.updatedItem()
    }
  },
  methods: {
    // 打开对话框
    showDialog (title, current) {
      this.dialogTitle = title
      this.dialogVisible = true

      if (title === '编辑') {
        this.currentRow = current.$index
        this.ruleForm = {
          ...current.row
        }
      }
    },
    // 关闭对话框
    closeDialog () {
      this.resetForm()
      this.getItem(this.YearTitle)
    },
    // 对话框内确定按钮
    submitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        if (this.dialogTitle === '添加') {
          this.tableData.push(this.ruleForm)
        } else if (this.dialogTitle === '编辑') {
          this.tableData.splice(this.currentRow, 1, this.ruleForm)
        }
        this.setItem(this.YearTitle)
        this.getItem(this.YearTitle)
        this.dialogVisible = false
      })
    },
    // 置空
    resetForm () {
      this.ruleForm = {
        yfa: '',
        yj: '',
        sj: '',
        tag: '未完成'
      }
      this.$refs.ruleForm.resetFields()
    },
    // 删除数据
    delRow (rowData) {
      this.$confirm(`确定删除序号为 ${rowData.$index + 1} 的数据吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(rowData.$index, 1)
        this.setItem(this.YearTitle)
        this.$message.success('删除成功!')
      }).catch(() => {})
    },
    getSummaries (param) {
      // columns 是每一列数据
      // data 是每一行数据
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '汇总：'
          return
        }
        if (index === 1 || index === 4) {
          sums[index] = data.length + '个月'
          return
        }

        // 第五列算法
        if (index === 5) {
          const Numarr = []
          const arr = []
          data.forEach(item => {
            const itemNum = item.xfmx.match(/\d+/g)// 匹配一个或多个数字
            Numarr.push(itemNum)
            arr.push(item.xfmx)
          })
          const brr = []
          arr.forEach(item => item.includes(',') ? brr.push(...item.split(',')) : brr.push(item))
          const newBrr = [...new Set(brr.map(item => item.replace(/\d+/g, '')))]

          const keywords = [...newBrr] // 关键词数组

          const newObj = {}

          for (const key of newBrr) {
            if (keywords.includes(key)) {
              newObj[key] = brr.filter(item => item.startsWith(key)).map(item => parseInt(item.split(key)[1]))
              newObj[key] = newObj[key].reduce((a, b) => a + b, 0)
            } else {
              newObj[key] = null
            }
          }
          for (const key in newObj) {
            if (newObj[key] > 9999) {
              newObj[key] = Math.floor(newObj[key] / 1000) / 10 + '万'
            }
          }
          const ultimate = { ...newObj }
          const result = Object.keys(ultimate).map(key => key + ultimate[key])
          sums[index] = `${result}`
          return
        }

        // 普遍算法
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          const num = sums[index] > 9999 ? (Math.floor(sums[index] / 1000) / 10) + '万' : sums[index]

          sums[index] = num + '元'
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    // 获取选择的年
    getTitleFn (Year) {
      this.YearTitle = Year
    },
    // 获取本地数据
    getItem (Year) {
      this.tableData = JSON.parse(localStorage.getItem(`${Year}database`))
    },
    setItem (Year) {
      localStorage.setItem(`${Year}database`, JSON.stringify(this.tableData))
    },
    updatedItem () {
      this.$nextTick(() => {
        if (localStorage.getItem(`${this.YearTitle}database`)) {
          this.getItem(this.YearTitle)
        } else {
          this.setItem(this.YearTitle)
        }
      })
    },
    // 导入的数据
    importData (value) {
      value.forEach(item => {
        this.tableData.push(item)
      })
      this.setItem(this.YearTitle)
      this.$message.success('批量导入数据成功!')
    }
  }
}
</script>
